package com.authine.cloudpivot.ext.applicationservice.report;

import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.cola.exception.BizException;
import com.alibaba.cola.exception.Exceptions;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.enums.inquiry.InquiryStatusEnum;
import com.authine.cloudpivot.ext.model.ReportRecord;
import com.authine.cloudpivot.ext.utils.BoServiceUtils;
import com.authine.cloudpivot.ext.utils.system.ReportUtils;
import com.authine.common.util.DateUtils;
import com.authine.mvp.app.launcher.dto.bo.query.expression.Operator;
import com.authine.mvp.app.launcher.dto.bo.response.BO;
import com.authine.mvp.app.launcher.dto.bo.response.BOList;
import com.authine.mvp.app.launcher.dto.errorcode.ErrorCodeEnum;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.authine.hermes.app.launcher.service.ApplicationServiceFoundation.CUSTOM_SERVICE;

/**
 * @ClassName InquiryReportService
 * @Description: 我的询价导出
 * @Author fj
 * @Date 2021/9/3
 * @Version V1.0
 **/
@Path("InquiryReportService")
@Slf4j
public class InquiryReportService {
    /**
     * 我的询价-报价中-导出报价商品/我的询价-全部-导出报价商品
     *
     * @param record 报表导出数据
     * @return 导出
     */
    @Path("quotationGoodsReport")
    @POST
    @Operation(summary = "我的询价-报价中-导出报价商品/我的询价-全部-导出报价商品", tags = CUSTOM_SERVICE)
    public SingleResponse<BO> quotationGoodsReport(@Parameter ReportRecord record) {
        if (StringUtils.isEmpty(record.getType())) {
            throw new BizException("报表导出类型不正确");
        }
        if (StringUtils.isEmpty(record.getCode())) {
            throw new BizException("报表导出文件不正确");
        }
        List<Map<String, Object>> reportList = Lists.newArrayList();// 报表数据
        List<String> inquiryGoodsList = Lists.newArrayList();// 符合要求的询价商品id

        // 通过询价商品id获取询价商品
        SingleResponse<BOList> inquiryGoodsBOList = BoServiceUtils.findListByIn(ModelConst.T_INQUIRY_GOODS, "id", record.getIds());
        log.info("-----------------------通过询价商品id获取询价商品列表：{}------------------------", JSONObject.toJSONString(inquiryGoodsBOList));
        if (!inquiryGoodsBOList.isSuccess()) {
            Exceptions.throwBizException(ErrorCodeEnum.BO_LIST_ERROR);
        }
        if (inquiryGoodsBOList.getData().getTotal() > 0) {
            List<String> inquiryIdList = inquiryGoodsBOList.getData().getData().stream()
                    .map(inquiryGoodsMap -> String.valueOf(inquiryGoodsMap.get("inquiry_id")))
                    .distinct()
                    .collect(Collectors.toList());
            // 通过询价单id获取询价单数据
            SingleResponse<BOList> inquiryBOList = BoServiceUtils.findListByIn(ModelConst.T_INQUIRY, "id", inquiryIdList);
            log.info("-----------------------通过询价单id获取询价单列表：{}------------------------", JSONObject.toJSONString(inquiryBOList));
            Map<String, Object> inquiry;
            // 取非密封报价、当前时间小于截止日期、询价商品状态为报价中的数据
            for (Map<String, Object> goodsMap : inquiryGoodsBOList.getData().getData()) {
                // 通过询价商品的询价单id找到对应的询价单
                inquiry = inquiryBOList.getData().getData().stream()
                        .filter(inquiryMap -> String.valueOf(inquiryMap.get("id")).equals(String.valueOf(goodsMap.get("inquiry_id"))))
                        .collect(Collectors.toList())
                        .get(0);
                if ("0".equals(String.valueOf(inquiry.get("quote_hermetic_strategy")))
                        || System.currentTimeMillis() > DateUtils.parseDate(String.valueOf(inquiry.get("expire"))).getTime()
                        || !InquiryStatusEnum.INQUIRY_GOODS_3_QUOTING.getCode().equals(String.valueOf(goodsMap.get("inquiry_goods_status")))) {
                    inquiryGoodsList.add(String.valueOf(goodsMap.get("id")));
                }
            }
        }
        if (inquiryGoodsList.size() > 0) {
            // 通过询价商品id查询报价商品
            String[] columnNames = new String[]{"inquiry_goods_id", "price"};
            Operator[] operators = new Operator[]{Operator.IN, Operator.IS_NOT_NULL};
            Object[] columnValues = new Object[]{inquiryGoodsList, null};
            SingleResponse<BOList> quotationBOList = BoServiceUtils.findListByComplex(ModelConst.T_QUOTATION_GOODS, columnNames, columnValues, operators);
            log.info("-----------------------通过询价商品id获取报价商品列表：{}------------------------", JSONObject.toJSONString(quotationBOList));
            Map<String, Object> dataMap;
            for (Map<String, Object> quotationMap : quotationBOList.getData().getData()) {
                dataMap = Maps.newHashMap();
                dataMap.put("id", String.valueOf(quotationMap.get("id")));
                dataMap.put("inquiryGoodsId", String.valueOf(quotationMap.get("inquiry_goods_id")));
                dataMap.put("vendorOrganizationName", quotationMap.get("vendor_organization_name"));
                dataMap.put("name", String.valueOf(quotationMap.get("name")));
                dataMap.put("brand", String.valueOf(quotationMap.get("brand")));
                dataMap.put("model", String.valueOf(quotationMap.get("model")));
                dataMap.put("spec", quotationMap.get("spec") == null ? "" : String.valueOf(quotationMap.get("spec")));
                dataMap.put("price", quotationMap.get("price") == null ? 0d : ((BigDecimal) quotationMap.get("price")).doubleValue());
                dataMap.put("amount", quotationMap.get("amount") == null ? 0d : ((BigDecimal) quotationMap.get("price")).doubleValue());
                dataMap.put("pretaxAmount", quotationMap.get("pretax_amount") == null ? 0d : ((BigDecimal) quotationMap.get("pretax_amount")).doubleValue());
                dataMap.put("pretaxPrice", quotationMap.get("pretax_price") == null ? 0d : ((BigDecimal) quotationMap.get("pretax_price")).doubleValue());
                dataMap.put("delivery", quotationMap.get("delivery") == null ? 0d : ((BigDecimal) quotationMap.get("delivery")).doubleValue());
                dataMap.put("num", quotationMap.get("num") == null ? 0d : ((BigDecimal) quotationMap.get("num")).doubleValue());
                dataMap.put("unit", quotationMap.get("unit") == null ? "" : String.valueOf(quotationMap.get("unit")));
                dataMap.put("packageNum", quotationMap.get("package_num") == null ? 0d : ((BigDecimal) quotationMap.get("package_num")).doubleValue());
                dataMap.put("packageUnit", quotationMap.get("package_unit") == null ? "" : String.valueOf(quotationMap.get("package_unit")));
                dataMap.put("freight", quotationMap.get("freight") == null ? 0d : ((BigDecimal) quotationMap.get("freight")).doubleValue());
                dataMap.put("pretaxFreight", quotationMap.get("pretax_freight") == null ? 0d : ((BigDecimal) quotationMap.get("pretax_freight")).doubleValue());
                dataMap.put("taxPayableFreight", quotationMap.get("tax_payable_freight") == null ? 0d : ((BigDecimal) quotationMap.get("tax_payable_freight")).doubleValue());
                dataMap.put("taxPayable", quotationMap.get("tax_payable") == null ? 0d : ((BigDecimal) quotationMap.get("tax_payable")).doubleValue());
                dataMap.put("taxRate", quotationMap.get("tax_rate") == null ? 0d : new BigDecimal(String.valueOf(quotationMap.get("tax_rate"))).doubleValue());
                dataMap.put("total", quotationMap.get("total") == null ? 0d : ((BigDecimal) quotationMap.get("total")).doubleValue());
                dataMap.put("pretaxTotal", quotationMap.get("pretax_total") == null ? 0d : ((BigDecimal) quotationMap.get("pretax_total")).doubleValue());
                dataMap.put("address", quotationMap.get("address") == null ? "" : String.valueOf(quotationMap.get("address")));
                dataMap.put("description", quotationMap.get("description") == null ? "" : String.valueOf(quotationMap.get("description")));
                reportList.add(dataMap);
            }
        }
        return ReportUtils.exportReport(record.getCode(), record.getType(), reportList);
    }

    /**
     * 我的询价-报价中-导出询价商品/我的报价-待参与-导出
     *
     * @param record 报表导出数据
     * @return 导出
     */
    @Path("inquiryGoodsReport")
    @POST
    @Operation(summary = "我的询价-报价中-导出询价商品/我的报价-待参与-导出", tags = CUSTOM_SERVICE)
    public SingleResponse<BO> inquiryGoodsReport(@Parameter ReportRecord record) {
        if (StringUtils.isEmpty(record.getType())) {
            throw new BizException("报表导出类型不正确");
        }
        if (StringUtils.isEmpty(record.getCode())) {
            throw new BizException("报表导出文件不正确");
        }
        List<Map<String, Object>> reportList = Lists.newArrayList();// 报表数据
        // 通过询价商品id获取询价商品列表
        SingleResponse<BOList> inquiryGoodsBOList = BoServiceUtils.findListByIn(ModelConst.T_INQUIRY_GOODS, "id", record.getIds());
        log.info("-----------------------通过询价商品id获取询价商品列表：{}------------------------", JSONObject.toJSONString(inquiryGoodsBOList));
        if (inquiryGoodsBOList.getData().getTotal() > 0) {
            Map<String, Object> dataMap;
            for (Map<String, Object> inquiryGoodsMap : inquiryGoodsBOList.getData().getData()) {
                dataMap = Maps.newHashMap();
                dataMap.put("id", String.valueOf(inquiryGoodsMap.get("id")));
                dataMap.put("inquiryId", String.valueOf(inquiryGoodsMap.get("inquiry_id")));
                dataMap.put("name", String.valueOf(inquiryGoodsMap.get("name")));
                dataMap.put("brand", String.valueOf(inquiryGoodsMap.get("brand")));
                dataMap.put("model", String.valueOf(inquiryGoodsMap.get("model")));
                dataMap.put("delivery", inquiryGoodsMap.get("delivery") == null ? 0 : ((BigDecimal) inquiryGoodsMap.get("delivery")).intValue());
                dataMap.put("num", inquiryGoodsMap.get("num") == null ? 0d : ((BigDecimal) inquiryGoodsMap.get("num")).doubleValue());
                dataMap.put("unit", inquiryGoodsMap.get("unit") == null ? "" : String.valueOf(inquiryGoodsMap.get("unit")));
                dataMap.put("packageNum", inquiryGoodsMap.get("package_num") == null ? 0d : ((BigDecimal) inquiryGoodsMap.get("package_num")).doubleValue());
                dataMap.put("packageUnit", inquiryGoodsMap.get("package_unit") == null ? "" : String.valueOf(inquiryGoodsMap.get("package_unit")));
                dataMap.put("description", inquiryGoodsMap.get("description") == null ? "" : String.valueOf(inquiryGoodsMap.get("description")));
                dataMap.put("spec", inquiryGoodsMap.get("spec") == null ? "" : String.valueOf(inquiryGoodsMap.get("spec")));
                dataMap.put("sku", inquiryGoodsMap.get("sku") == null ? "" : String.valueOf(inquiryGoodsMap.get("sku")));
                dataMap.put("barCode", inquiryGoodsMap.get("bar_code") == null ? "" : String.valueOf(inquiryGoodsMap.get("bar_code")));
                dataMap.put("memo", inquiryGoodsMap.get("memo") == null ? "" : String.valueOf(inquiryGoodsMap.get("memo")));
                dataMap.put("address", inquiryGoodsMap.get("address") == null ? "" : String.valueOf(inquiryGoodsMap.get("address")));
                dataMap.put("url", inquiryGoodsMap.get("url") == null ? "" : String.valueOf(inquiryGoodsMap.get("url")));
                dataMap.put("platform_category_name", inquiryGoodsMap.get("platform_category_name") == null ? "" : String.valueOf(inquiryGoodsMap.get("platform_category_name")));
                reportList.add(dataMap);
            }
        }
        return ReportUtils.exportReport(record.getCode(), record.getType(), reportList);
    }
}
